package es.usc.citius.servando.calendula.settings;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.preference.Preference;
import android.support.v7.preference.PreferenceFragmentCompat;
import android.widget.Toast;

import es.usc.citius.servando.calendula.CalendulaActivity;
import es.usc.citius.servando.calendula.R;
import es.usc.citius.servando.calendula.settings.database.DatabasePrefsFragment;
import es.usc.citius.servando.calendula.util.LogUtil;

import static android.support.v4.app.FragmentTransaction.TRANSIT_FRAGMENT_FADE;

public class CalendulaSettingsActivity extends CalendulaActivity
        implements PreferenceFragmentCompat.OnPreferenceStartFragmentCallback{

    private final String TAG = "CalendulaSettingsActivity";
    public static String EXTRA_SHOW_DB_DIALOG = "show_db_dialog"; //TODO actually do something with this

    @Override
    public boolean onPreferenceStartFragment(PreferenceFragmentCompat pref, Preference preference) {
        try {
            LogUtil.d(TAG, "onPreferenceStartFragment: pref fragment class is ${pref.fragment}");
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            Fragment fragment = (Fragment)Class.forName(String.valueOf(pref.getTargetFragment())).newInstance();
            transaction.setTransition(TRANSIT_FRAGMENT_FADE);
            transaction.replace(R.id.content_layout, fragment);
            transaction.addToBackStack(null);
            transaction.commit();
        } catch (Exception e) {
            LogUtil.e(TAG, "onPreferenceStartFragment: ", e);
            Toast.makeText(this, R.string.message_generic_error, Toast.LENGTH_SHORT).show();
        }
        return true;
    }

    @Override
    protected void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);
        setupStatusBar(ContextCompat.getColor(this, R.color.dark_grey_home));

        setupToolbar(
                getString(R.string.title_activity_settings),
                ContextCompat.getColor(this, R.color.dark_grey_home)
        );

        if (!processIntent()) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.content_layout, new MainPrefsFragment()).commit();
        }
    }

    /**
     * @return `true` if the initialization of the Activity should be interrupted (not load the main fragment)
     */
    private boolean processIntent() {
        if (getIntent().getBooleanExtra(EXTRA_SHOW_DB_DIALOG, false)) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.content_layout, new DatabasePrefsFragment()).commit();
            return true;
        }
        return false;
    }
}
